#include "switchdelegate.h"

#include <QPainter>
#include <QMouseEvent>
#include <QPropertyAnimation>
#include <QCheckBox>
#include <QApplication>
#include <QDebug>

SwitchDelegate::SwitchDelegate(QObject *parent, int column)
    : QStyledItemDelegate(parent)
    , m_checkBox(new QCheckBox())
    , m_delegateColumn(column)
{
    QString qss = "QCheckBox::indicator:unchecked{ \
                   border: none; background-color: transparent; \
                   image:url(:/image/switch_close.png); \
                   } \
                   QCheckBox::indicator:checked { \
                   border: none; background-color: transparent; \
                   image: url(:/image/switch_open.png); \
                   }";
    m_checkBox.data()->setStyleSheet(qss);
}

void SwitchDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                           const QModelIndex &index) const
{
    QStyleOptionViewItem viewOption(option);
    initStyleOption(&viewOption, index);
    if (option.state.testFlag(QStyle::State_HasFocus))
        viewOption.state = viewOption.state ^ QStyle::State_HasFocus;

    // 绘制单元格背景
    QStyledItemDelegate::paint(painter, viewOption, index);

    if (index.column() == m_delegateColumn)
    {
        bool data = index.model()->data(index, Qt::UserRole).toBool();

        QStyleOptionButton checkBoxStyle;
        checkBoxStyle.text = data ? "启用" : "禁用";
        checkBoxStyle.state = data ? QStyle::State_On : QStyle::State_Off;
        checkBoxStyle.state |= QStyle::State_Enabled;
        checkBoxStyle.rect = option.rect;

        m_checkBox.data()->style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &checkBoxStyle, painter, m_checkBox.data());
//        m_checkBox.data()->style()->drawControl(QStyle::CE_CheckBox, &checkBoxStyle, painter, m_checkBox.data());
    }
}

bool SwitchDelegate::editorEvent(QEvent *event, QAbstractItemModel *model,
                                 const QStyleOptionViewItem &option,
                                 const QModelIndex &index)
{
    QRect decorationRect = option.rect;

    QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
    if (event->type() == QEvent::MouseButtonRelease && decorationRect.contains(mouseEvent->pos()))
    {
        if (index.column() == m_delegateColumn)
        {
            bool data = model->data(index, Qt::UserRole).toBool();
            model->setData(index, !data, Qt::UserRole);
            emit stateChanged(index, !data);
        }
    }

    return QStyledItemDelegate::editorEvent(event, model, option, index);
}


